﻿using System;
using Orchard.Environment.Extensions;
using Orchard.Localization.Services;
using Orchard.Mvc;
using Orchard.Widgets.Services;

namespace Vitus.Localization.RuleEngine
{
    [OrchardFeature("Vitus.CultureLayerRule")]
    public class CultureRuleProvider : IRuleProvider
    {
        private readonly ICultureManager _cultureManager;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public CultureRuleProvider(ICultureManager cultureManager, IHttpContextAccessor httpContextAccessor)
        {
            _cultureManager = cultureManager;
            _httpContextAccessor = httpContextAccessor;
        }

        public void Process(RuleContext ruleContext)
        {
            if (!String.Equals(ruleContext.FunctionName, "culture", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            string culture = Convert.ToString(ruleContext.Arguments[0]);

            var httpContext = _httpContextAccessor.Current();
            string currentCulture = _cultureManager.GetCurrentCulture(httpContext);

            ruleContext.Result = culture.EndsWith("*")
                ? currentCulture.StartsWith(culture.TrimEnd('*'), StringComparison.OrdinalIgnoreCase)
                : string.Equals(currentCulture, culture, StringComparison.OrdinalIgnoreCase);
        }
    }
}